package com.ns.dcjh.utils;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;

/**
 * @Author chrisz
 * @Description
 * @CreateDate 2019/7/20
 * @Version 1.0
 */

public class ClipboardUtils {
    /**
     * 设置剪贴板内容
     * @param context
     * @param text
     */
    public static void setText(Context context, String text) {
        ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        if (cm == null)     return;
        ClipData mClipData = ClipData.newPlainText("Label", text);
        cm.setPrimaryClip(mClipData);
    }

    /**
     * 读取剪贴板内容
     * @param context
     * @return
     */
    public static String getText(Context context) {
        ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        if (cm == null || !cm.hasPrimaryClip())   return "";
        ClipData data = cm.getPrimaryClip();
        ClipData.Item item = data.getItemAt(0);
        return item.getText() != null ? item.getText().toString() : "";
    }

    /**
     * 清除剪贴板
     */
    public static void cleanUp(Context context) {
        ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        if (cm == null)     return;

        try {
            ClipData mClipData = ClipData.newPlainText("Label", null);
            cm.setPrimaryClip(mClipData);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
